package com.wwc.bwcj.fragment

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Button
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager2.widget.ViewPager2
import com.google.android.material.textfield.TextInputEditText
import com.wwc.bwcj.R
import com.wwc.bwcj.adapter.BannerAdapter
import com.wwc.bwcj.adapter.ProductAdapter
import com.wwc.bwcj.entity.CartProduct
import com.wwc.bwcj.entity.Product
import com.wwc.bwcj.util.CartManager
import com.wwc.bwcj.util.SelectSpecDialog

/**
 * 点单页面
 */
class OrderFragment : Fragment() {
    private lateinit var recyclerView: RecyclerView
    private lateinit var viewPagerBanner: ViewPager2
    private lateinit var indicatorContainer: LinearLayout
    private val bannerImages = listOf( //轮播图图片列表
        R.drawable.banner1,
        R.drawable.banner2,
        R.drawable.banner3
    )
    private val handler = Handler(Looper.getMainLooper()) //用于定时切换轮播图
    private var currentPage = 0 //当前轮播图页面索引
    private val delayMillis: Long = 3000 // 3秒切换一次

    // 轮播图自动切换的Runnable
    private val updateRunnable = object : Runnable {
        override fun run() {
            if (currentPage >= bannerImages.size) {
                currentPage = 0
            }
            viewPagerBanner.currentItem = currentPage++
            updateIndicator()
            handler.postDelayed(this, delayMillis)
        }
    }

    private lateinit var searchEditText: TextInputEditText //商品搜索输入框
    private lateinit var adapter: ProductAdapter //商品列表适配器
    private val products = getProducts() //本地商品列表

    //页面初始化
    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        val view = inflater.inflate(R.layout.fragment_order, container, false)

        recyclerView = view.findViewById(R.id.recycler_view)
        viewPagerBanner = view.findViewById(R.id.view_pager_banner)
        indicatorContainer = view.findViewById(R.id.banner_indicator)
        searchEditText = view.findViewById(R.id.search_edit_text)

        // 设置RecyclerView的布局管理器
        recyclerView.layoutManager = LinearLayoutManager(context)

        // 创建适配器并设置数据
        adapter = ProductAdapter(products)
        recyclerView.adapter = adapter

        // 设置轮播图
        setupBanner()

        // 设置搜索监听
        // 在 TextWatcher 中增加输入验证
        searchEditText.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {}

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                filterProducts(s?.toString() ?: "")
            }

            override fun afterTextChanged(s: Editable?) {}
        })
        // 搜索栏焦点设置
        searchEditText.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                // 点击时隐藏提示，只显示输入内容
                searchEditText.hint = null
            } else {
                // 失去焦点时恢复提示
                searchEditText.hint = "推荐：伯牙绝弦"
            }
        }
        return view
    }

    // 轮播图设置
    private fun setupBanner() {
        // 设置轮播图适配器
        val bannerAdapter = BannerAdapter(bannerImages)
        viewPagerBanner.adapter = bannerAdapter

        // 设置页面切换监听器来更新指示器
        viewPagerBanner.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
            override fun onPageSelected(position: Int) {
                super.onPageSelected(position)
                currentPage = position
                updateIndicator()
            }
        })
        // 开始自动轮播
        startAutoScroll()
    }

    // 更新指示器选中状态
    private fun updateIndicator() {
        for (i in 0 until indicatorContainer.childCount) {
            val imageView = indicatorContainer.getChildAt(i) as ImageView
            if (i == currentPage % bannerImages.size) {
                imageView.setImageResource(R.drawable.indicator_dot_selected)
            } else {
                imageView.setImageResource(R.drawable.indicator_dot_unselected)
            }
        }
    }

    // 开始自动轮播
    private fun startAutoScroll() {
        handler.postDelayed(updateRunnable, delayMillis)
    }

    // 根据输入关键字过滤商品，增加异常处理
    private fun filterProducts(query: String) {
        val filteredList = if (query.isEmpty()) {
            products
        } else {
            products.filter { it.name.contains(query, ignoreCase = true) }
        }
        adapter.submitList(filteredList)
    }

    // 初始数据加载，提供静态商品数据
    private fun getProducts(): List<Product> {
        return listOf(
            Product(
                "伯牙绝弦",
                "霸王茶姬经典款&畅销款,累计销量突破12亿杯* 原叶茶胚为经过三到五...",
                "¥16起",
                R.drawable.product_byjx
            ),
            Product(
                "栀香柠",
                "栀子绿茶搭配香水柠檬，茶汤甘醇清冽..",
                "¥16起",
                R.drawable.product_zxn
            ),
            Product(
                "琥珀光",
                "香水柠檬和大红袍的绝佳组合，甄选优质大红袍，滋味醇厚...",
                "¥18起",
                R.drawable.product_hpg
            ),
            Product(
                "白雾红尘",
                "优质大红袍，茶香优而强烈，芬芳持久",
                "¥17起",
                R.drawable.product_bwhc
            ),
            Product(
                "桂馥兰香",
                "优选闽南乌龙茶底，自然桂花香搭配中焙火乌龙，醇厚清甜，口感细腻",
                "¥15起",
                R.drawable.product_gflx
            ),
            Product(
                "山野栀子",
                "茶汤清甜醇厚，栀子花香清冷温柔，搭配优质",
                "¥12起",
                R.drawable.product_syzz
            ),
            Product(
                "花田乌龙",
                "茶底升级，选用闽南乌龙茶底，加入花田乌龙，茶汤清甜，有种花田乌...",
                "¥16起",
                R.drawable.product_htwl
            ),
            Product(
                "万里木兰",
                "精选不同海拔的锡兰红茶进行拼配，茶香高长...",
                "¥16起",
                R.drawable.product_wlml
            )
        )
    }

    override fun onPause() {
        super.onPause()
        handler.removeCallbacks(updateRunnable)
    }

    override fun onResume() {
        super.onResume()
        startAutoScroll()
    }

    override fun onDestroy() {
        super.onDestroy()
        handler.removeCallbacks(updateRunnable)
    }
}



